
var SystemCommon = function(){
	return {
		//初始化左边链接点击
		initClick : function(){
			$(".left-menu .showRight").unbind("click");
			$(".left-menu .showRight").on('click',function(){
				var url=$(this).data("url");
				window.location.href = ctx +"/"+url;
//				SystemCommon.showContent(url);
			});
			
			
			SystemCommon.updatePwd();
			SystemCommon.outSystem();
			SystemCommon.menuCloseBtn();
			//SystemCommon.clickReset();
			SystemCommon.menuScroll();
		},

		// 菜单超出自动滚动
        menuScroll: function() {
            let menuTree = $('.menu-tree');

            let openTree = menuTree.find('.tree-item.open');
            if (openTree.length > 0) {
                let treeOffset = openTree.position().top;
                let menuHeight = menuTree.height();
                let len = openTree.children('ul').find('li').length;
                let scrollHeight = treeOffset - menuHeight + 64 + len * 48;
                // console.log(treeOffset);
                // console.log(menuHeight);
                // console.log(scrollHeight);
                // console.log(len);

                menuTree.animate({ scrollTop: scrollHeight }, 300);
            }
        },

        // 重置
        formReset: function(id) {
            var ele;

            id ? (ele = id) : (ele = '.query-frame-wrap');

            // input
            $(ele).find('input').val('');

            // select
            $(ele).find("select option").removeAttr('selected');
            $(ele).find("select option").eq(0).attr('selected','selected');

            // select2
            $(".select2-frame").empty()
                .append("<option value=''></option>")
                .trigger('change.select2');
        },

        // 触发重置
        clickReset: function() {
            $('.query-button img').eq(1).click(function() {

            	SystemCommon.formReset();
            })
        },
		
		//更新密码
		updatePwd : function(){
			
			$(".updatePwd").on("click",function(){
				
				$(".updatePwdModal").modal();
				
			});
			
			$(".password_form .yes").on("click",function(){
				
				$(".password_form").data("bootstrapValidator").validate();
				var flag = $(".password_form").data("bootstrapValidator").isValid();
				console.log(flag);
				if(!flag){
					//未通过验证
					return false;
				}
				
				$.ajax({
		    		url:ctx + "/updatePwd/update.mvc",
					dataType: "json",
					data: $(".password_form").serialize(),
					success:function(data){
						if(data.result == true){
							DialogUtil.success("更改成功");
							
							window.location.href = ctx + "/login";
							
			             }else{
			            	 DialogUtil.error("更改失败");
			             }
					}
				});
			});
			
			$(".password_form").bootstrapValidator({
				message: 'This value is not valid',
	            live: 'enabled',
//	            live: 'submitted',
	            fields: {/*验证*/
	            	password: {
	                    message:'密码无效',
	                    validators: {
	                        notEmpty: {
	                            message: '密码不能为空'
	                        },
	                        regexp: {
	                        	regexp: /^[a-zA-Z0-9]+$/,
	                            message: '密码只能包含字母、数字，区分大小写'
	                        },
	                        threshold :  1 , //有1字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
	                        remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}  
	                            url: ctx+'/validPwd/get.mvc',//验证地址
	                            message: '密码错误',//提示消息
	                            delay :  2000,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
	                            type: 'POST'//请求方式
	                        },
	                    }
	                },
	                new_password: {
	                    message:'密码无效',
	                    validators: {
	                        notEmpty: {
	                            message: '密码不能为空'
	                        },
	                        identical: {//相同
	                            field: 're_new_password',
	                            message: '两次密码不一致'
	                        },
	                        stringLength: {
	                            min: 6,
	                            max: 20,
	                            message: '密码长度必须在6到20之间'
	                        },
	                        remote: {
	                            url: ctx+'/validNewPwd/get.mvc',//验证地址
	                            message: '新密码与原密码一致',//提示消息
	                            delay :  1000,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
	                            type: 'POST'//请求方式
	                        },
	                        regexp: {
	                        	regexp: /^[a-zA-Z0-9]+$/,
	                            message: '密码只能包含字母、数字，区分大小写'
	                        }
	                    }
	                },
	                re_new_password: {
	                    message:'密码无效',
	                    validators: {
	                        notEmpty: {
	                            message: '密码不能为空'
	                        },
	                        identical: {//相同
	                            field: 'new_password',
	                            message: '两次密码不一致'
	                        },
	                        stringLength: {
	                            min: 6,
	                            max: 20,
	                            message: '密码长度必须在6到20之间'
	                        },
	                        regexp: {
	                        	regexp: /^[a-zA-Z0-9]+$/,
	                            message: '密码只能包含字母、数字，区分大小写'
	                        }
	                    }
	                },
	            }
			});
			//模态框消失清空信息
			$(".password_form").on("hidden.bs.modal",function(e){
				$('.password_form input').each(function() {
					if ($(this).val() != "" || $(this).prop('checked') == true) {
						$(this).val("").prop('checked', false);
					}
				});
				$('.password_form').data('bootstrapValidator').destroy();
				SystemCommon.updatePwd();
			});
		},
		//登出系统.
		outSystem : function (){
			$(".outSystem").on("click","",function(){
				DialogUtil.ok_and_cancel( "确定退出系统？",function(){
                    window.location.href = ctx + "/logout";
				});
				
			});
		},
		getSystemUser :function() {
			var select2 = $('.systemUserSearch').select2({
				  ajax: {
				    url: ctx +'/system/user/getSysUserList/get.mvc',
				    dataType: 'json',
					aynsc :false,
				    data: function (params) {
				        var query = {
				          search: params.term,
				          num: params.page || 1,
				          size:10
				        };
				        // Query parameters will be ?search=[term]&page=[page]
				        return query;
				    },
				    processResults: function (response) {
				        // Tranforms the top-level key of the response object from 'items' to 'results'
				    	var test =new Array();
				    	if(response&&response.data){
				    		var data = response.data;
				    		for ( var int = 0; int < data.length; int++) {
								var obj=new Object();
								obj.id=data[int].pkId;
								obj.text=data[int].truename;
								test.push(obj);
							}
					    	var result = {
					    		results: test
					    	};
					        return result;
				    	}
				    	return null;
				    	
				      },
				    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
				      cache: true
				    
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0
			});
			return select2;

		},
		//获取系统字典下拉框
		getSysDict : function (parentKey,eleClass) {
            $.ajax({
                url: ctx +'/system/dict/getSysDictsByParentKey/get.mvc',
                type:"post",
                aysnc: true,
                dataType:'json',
                data : {
                	parentKey:parentKey
				},
                success : function(response){
                	if(response&&response.data) {
                		var _data = response.data;
                        $("."+eleClass).append("<option value='' >请选择</option>");
                        for (var i = 0; i < _data.length; i++) {
                            $("."+eleClass).append("<option value='"+_data[i].dictKey+"' >" + _data[i].dictValue + "</option>");
                        }
					}

                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    console.log(errorThrown);
                    alert("系统错误");
                }
            });
        },
		getEqModelList : function () {
            SystemCommon._getEqModelList();
            $("#modelSearch").on("click",function(){
                SystemCommon._getEqModelList();
            });
            $(".model-search").keypress(function (e) {
                if (e.which === 13) {
                    $("#modelSearch").trigger("click");
                }
            });
        },
        _getEqModelList:function () {
            $.ajax({
                url : ctx + '/tool/config/getEqModelList/get.mvc',
                type : "post",
                dataType : 'json',
                data : {
                    modelCode:$("#modelCode").val()
                },
                success : function(response) {
                    //debugger;
                    if (response.result === true&&response.data) {
                        var modelList = response.data;
                        var eqModelList = $("#eqModelList");
                        eqModelList.empty();
                        for (var i = 0;i<modelList.length;i++) {
                            var li = $("<li class='eq-model' data-modelcode='"+modelList[i].modelCode+"'>"+modelList[i].modelCode+"</li>");
                            eqModelList.append(li);
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown);
                    DialogUtil.error("系统错误");
                }
            });
        },
		//获取工序名称
		getQueryOperation : function(){
			$('.operationSearch').select2({
				  ajax: {
				    url: ctx +'/system/operation/listAllOperation/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          search: params.term,
				          page: params.page || 1,
				          size:10
				        };
				        // Query parameters will be ?search=[term]&page=[page]
				        return query;
				    },
				    processResults: function (data) {
				        // Tranforms the top-level key of the response object from 'items' to 'results'
				    	var test =new Array();
				    	for ( var int = 0; int < data.length; int++) {
							var obj=new Object();
							obj.id=data[int].pkId;
							obj.text=data[int].name;
							test.push(obj);
						}
				    	var result = {
				    		results: test
				    	};
				        return result;
				      },
				    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
				      cache: true
				    
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0,
			});
		},
		//获取工序名称
		getMultipleQueryOperation : function(){
			$('.operationSearch').select2({
				  ajax: {
				    url: ctx +'/system/operation/listAllOperation/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          search: params.term,
				          page: params.page || 1,
				          size:10
				        };
				        // Query parameters will be ?search=[term]&page=[page]
				        return query;
				    },
				    processResults: function (data) {
				        // Tranforms the top-level key of the response object from 'items' to 'results'
				    	var test =new Array();
				    	for ( var int = 0; int < data.length; int++) {
							var obj=new Object();
							obj.id=data[int].pkId;
							obj.text=data[int].name;
							test.push(obj);
						}
				    	var result = {
				    		results: test
				    	};
				        return result;
				      },
				    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
				      cache: true
				    
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0,
			});
		},
		
		//点击下拉框--关键备件编码支持模糊查询
		getKeyPart : function(){
			var select2 =$('.partCode').select2({
				  ajax: {
				    url: ctx +'/part/info/listKeyPartAll/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          search: params.term,
				          page: params.page || 1,
				          size:10
				        };
				        return query;
				    },
				    processResults: function (data) {
				    	var partCodeArr =new Array();
				    	for ( var i = 0; i < data.length; i++) {
							var obj = new Object();
							obj.id=data[i].partCode;
							obj.text=data[i].partCode;
							partCodeArr.push(obj);
						}
				    	var result = {
				    		results: partCodeArr
				    	};
				        return result;
				      },
				      cache: true
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0,
			});
			return select2;
		},
		//改变备件编码
		changePartCode : function(){
			$(".partCode").on("change","",function(){
				$.ajax({
					url: ctx +'/part/info/getPartByPartCode/get.mvc',
				    type:"post", 
				    aysnc: true,
				    dataType:'json',
				    data: {
				    	partCode : $(".partCode").val()
				    },
				    success : function(response){
				    	console.log(response);
				    	$("#myModal input[name='partName']").val(response.data.partName);
				    	$("#myModal input[name='lifeUnit']").val(response.data.lifeUnit);
						$("#myModal input[name='partId']").val(response.data.pkId);
				    },
				    error: function(XMLHttpRequest, textStatus, errorThrown){
				    	alert("系统错误");
				    }
				});
				
			});
		},
		//获取工序名称
		getQueryOperationCode : function(){
			
			$('.operationCodeSearch').select2({
				  ajax: {
				    url: ctx +'/system/operation/listAllOperation/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          search: params.term,
				          page: params.page || 1,
				          size:10
				        };
				        // Query parameters will be ?search=[term]&page=[page]
				        return query;
				    },
				    processResults: function (data) {
				        // Tranforms the top-level key of the response object from 'items' to 'results'
				    	var test =new Array();
				    	for ( var int = 0; int < data.length; int++) {
							var obj=new Object();
							obj.id=data[int].pkId;
							obj.text=data[int].code;
							test.push(obj);
						}
				    	var result = {
				    		results: test
				    	};
				        return result;
				      },
				    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
				      cache: true
				    
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0,
			});
		},
		//查询所有的设备类别信息--只用于查询按钮
		getQueryEquipModel : function(){
			$('.queryEuqipModel').select2({
				  ajax: {
				    url: ctx +'/equipment/type/listAllModel/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          search: params.term,
				          page: params.page || 1,
				          size:10
				        };
				        return query;
				    },
				    processResults: function (data) {
				    	var equipModelArr =new Array();
				    	for ( var i = 0; i < data.length; i++) {
							var obj = new Object();
							obj.id=data[i].modelCode;
							obj.text=data[i].modelCode;
							equipModelArr.push(obj);
						}
				    	var result = {
				    		results: equipModelArr
				    	};
				        return result;
				      },
				      cache: true
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0,
			});
		},
		//查询所有的能耗设备编号--只用于查询按钮
		getQueryEnergy : function(){
			$('.energyCode').select2({
				  ajax: {
				    url: ctx +'/equipment/energy/listAllEquipmentEnergy/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          search: params.term,
				          page: params.page || 1,
				          size:10
				        };
				        return query;
				    },
				    processResults: function (data) {
				    	var energyArr =new Array();
				    	for ( var i = 0; i < data.length; i++) {
							var obj=new Object();
							obj.id=data[i].code;
							obj.text=data[i].code;
							energyArr.push(obj);
						}
				    	var result = {
				    		results: energyArr
				    	};
				        return result;
				      },
				      cache: true
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0,
			});
		},
		
		//设备查询 ---获取设备编号
		getQueryEquipCode : function(){
			var select2 = $('.queryEquipment').select2({
				  ajax: {
				    url: ctx +'/equipment/register/searchEquipmentByEquipCode/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          equipCode: params.term,
				          num: params.page || 1,
				          size:10
				        };
				        return query;
				    },
				    processResults: function (result) {

				    	var equipModelArr =new Array();
				    	for ( var i = 0; i < result.data.length; i++) {
							var obj = new Object();
							obj.id=result.data[i].equipCode;
							obj.text=result.data[i].equipCode;
							equipModelArr.push(obj);
						}
				    	var result = {
				    		results: equipModelArr,
				    		pagination :{
				    			more:result.result
				    		}
				    	};
				        return result;
				      },
				      cache: true
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0
			});
			return select2;
		},
		
		//时间控件
		getDate : function(day){
			var dayNum = 1;
			if (typeof(day) != "undefined")
			{
				dayNum=day;
			}
			$('.form_datetimeStart').val(new Date(new Date().getTime() - dayNum*24*60*60*1000).format('yyyy-MM-dd hh:mm:ss'));
			$('.form_datetimeEnd').val(new Date().format('yyyy-MM-dd hh:mm:ss'));
			$('.form_datetimeStart').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			});
			$('.form_datetimeEnd').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			});
		},
		//无默认时间
		getDateNull : function(e){
			$('.form_datetimeStart').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			});
			$('.form_datetimeEnd').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			});
		},
		//点击下拉框--设备型号信息
		getEmModel : function(){
			$.ajax({
				url: ctx +'/equipment/type/listAllModel/get.mvc',
			    type:"post", 
			    aysnc: true,
			    dataType:'json',
			    data : '',
			    success : function(data){
		    		for (var i = 0; i < data.length; i++) {
			    		 $("#myModal .emModelName").append("<option value='"+data[i].modelCode+"' >" + data[i].modelCode + "</option>");
			    	 };
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	console.log(data);
			    	alert("系统错误");
			    }
			});
		},
		//通过设备型号改变实时获取设备类别信息
		changeEmModel : function(){
			$(".emModelName").on("change","",function(){
				$.ajax({
					url: ctx +'/equipment/type/getEquipmentModelByEmModel/get.mvc',
				    type:"post", 
				    aysnc: true,
				    dataType:'json',
				    data: {
				    	emModel : $(".emModelName").val()
				    },
				    success : function(data){
				    	$("#myModal .operation").empty();
				    	
				    	//设备类别
				    	$("#myModal input[name='modelType']").val("");
				    	var value =data.modelType;
				    	
				    	if(value == "1"){
				    		$("#myModal input[name='modelType']").val("生产类");
				    		$(".operationDiv").show();
	                	}else if(value=="2"){
	                		$("#myModal input[name='modelType']").val("环境类");
	                		$(".operationDiv").hide();
	                	}else if(value=="3"){
	                		$("#myModal input[name='modelType']").val("能源类");
	                		$(".operationDiv").hide();
	                	}else if(value=="4"){
	                		$("#myModal input[name='modelType']").val("检测类");
	                		$(".operationDiv").hide();
	                	}else if(value=="5"){
	                		$("#myModal input[name='modelType']").val("生产辅助类");
	                		$(".operationDiv").show();
	                	}
				    	
				    	
				    	$("#myModal input[name='supplier']").val(data.supplier);
				    	
				    	$("#myModal input[name='ecRoute']").val(data.ecRoute);
				    	
				    	$(".form-group.collection_type").css("display","none");
				    	$("#myModal .plcProtocal").css("display","none");
				    	//显示对应的信息
				    	//采集方式
				    	var typeHtml="";
				    	var type =data.type+"";
				    	if(type.indexOf("1")!=-1){
				    		typeHtml+="PLC,";
				    		$("#myModal .plcProtocal").css("display","block");
				    	}
				    	if(type.indexOf("2")!=-1){
				    		typeHtml+="文件,";
				    		$(".form-group.file_addr").css("display","block");
				    	}
				    	if(type.indexOf("3")!=-1){
				    		typeHtml+="数据库,";
				    		$(".form-group.database_addr").css("display","block");
				    	}
				    	if(type.indexOf("4")!=-1){
				    		typeHtml+="上位机,";
				    		$(".form-group.upper").css("display","block");
				    	}
				    	$("#myModal input[name='collectionType']").val(typeHtml.substring(0, typeHtml.length-1));
				    	
				    	//关联处理工序，设备型号上的工序
				    	var html="";
	                	for(var i=0;i<data.operationList.length;i++){
	                		html+=data.operationList[i].opName+",";
	                	}
	                	$("#myModal input[name='operation']").val(html.substring(0,html.length-1));
	                	
	                	//工序的下拉
                        $("#myModal .operation").append("<option value='' >请选择</option>");
	                	for(var i=0;i<data.operationList.length;i++){
	                		$("#myModal .operation")
	                			.append("<option value='"+data.operationList[i].opId+"' >" + data.operationList[i].opName + "</option>");
	                	}
	                	
				    	
				    
				    },
				    error: function(XMLHttpRequest, textStatus, errorThrown){
				    	alert("系统错误");
				    }
				});
				
			});
		},
		//点击下拉框----获取所有的工序
		getOperation : function(){
			$.ajax({
				url: ctx +'/system/operation/listAllOperation/get.mvc',
			    type:"post", 
			    aysnc: true,
			    dataType:'json',
			    data : '',
			    success : function(data){
		    		for (var i = 0; i < data.length; i++) {
			    		 $("#myModal .operation").append("<option value='"+data[i].pkId+"' >" + data[i].name + "</option>");
			    	 };
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	console.log(data);
			    	alert("系统错误");
			    }
			});
		},
		
        //初始化opSelect2下拉框----获取所有的工序
		_initOpSelect2 : function () {
            var select2 = $(".operation").select2({
                ajax: {
                    url: ctx +'/system/operation/listAllOperation/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        var query = {
                            search: params.term,
                            num: params.page || 1,
                            size:10
                        };
                        return query;
                    },
                    processResults: function (result) {
                        var opArr =new Array();
                        for ( var i = 0; i < result.length; i++) {
                            var obj = new Object();
                            obj.id=result[i].pkId;
                            obj.text=result[i].name;
                            opArr.push(obj);
                        }
                        var result = {
                            results: opArr,
                            pagination :{
                                more:result.result
                            }
                        };
                        
                        return result;
                    },
                    cache: true
                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        //初始化lineSelect2下拉框----获取所有的产线
		_initLineSelect2 : function () {
            var select2 = $(".line").select2({
                ajax: {
                    url: ctx +'/factory/product/listAllLinesByFactoryId/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        var query = {
                        	factoryId : $(".factory").val(),
                            lineName: params.term,
                            num: params.page || 1,
                            size:10
                        };
                        return query;
                    },
                    processResults: function (result) {
                    	console.log(result);
                        var opArr =new Array();
                        for ( var i = 0; i < result.data.length; i++) {
                            var obj = new Object();
                            obj.id=result.data[i].pkId;
                            obj.text=result.data[i].lineName;
                            opArr.push(obj);
                        }
                        var result = {
                            results: opArr,
                            pagination :{
                                more:result.result
                            }
                        };
                        
                        return result;
                    },
                    cache: true
                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
		//点击下拉框----获取所有的厂区
		getFactory : function(){
			$(".line").empty();
			$.ajax({
				url: ctx +'/factory/factoryArea/listAllFactory/get.mvc',
			    type:"post", 
			    aysnc: true,
			    dataType:'json',
			    data : '',
			    success : function(data){
			    	$(".factory").append("<option value='' >请选择</option>");
		    		for (var i = 0; i < data.length; i++) {
			    		 $(".factory").append("<option value='"+data[i].pkId+"' >" + data[i].factoryName + "</option>");
			    	 };
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
		},
		//快捷时间
		changeShortcutTime:function () {
            $("#shortcutTime").on("change",function () {
            	var now = new Date(); //当前日期
            	var nowDayOfWeek = now.getDay(); //今天本周的第几天
            	var nowDay = now.getDate(); //当前日
            	var nowMonth = now.getMonth(); //当前月
            	var nowYear = now.getYear(); //当前年
            	nowYear += (nowYear < 2000) ? 1900 : 0; //
            	var lastMonthDate = new Date(); //上月日期
            	lastMonthDate.setDate(1);
            	lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
            	var lastYear = lastMonthDate.getYear();
            	var lastMonth = lastMonthDate.getMonth();
            	//格式化日期：yyyy-MM-dd
            	function formatDate(date) {
            	    var myyear = date.getFullYear();
            	    var mymonth = date.getMonth() + 1;
            	    var myweekday = date.getDate();
            	    if (mymonth < 10) {
            	        mymonth = "0" + mymonth;
            	    }
            	    if (myweekday < 10) {
            	        myweekday = "0" + myweekday;
            	    }
            	    return (myyear + "-" + mymonth + "-" + myweekday);
            	}
            	//获得某月的天数
            	function getMonthDays(myMonth) {
            	    var monthStartDate = new Date(nowYear, myMonth, 1);
            	    var monthEndDate = new Date(nowYear, myMonth + 1, 1);
            	    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
            	    return days;
            	}
            	function getPriorSeasonFirstDay(year,month){    
                    var quarterMonthStart=0;    
                    var spring=0; //春    
                    var summer=3; //夏    
                    var fall=6;   //秋    
                    var winter=9;//冬    
                    //月份从0-11    
                    switch(month){//季度的其实月份    
                    case 0:    
                        //如果是第一季度则应该到去年的冬季    
                          year--;    
                          month=spring;    
                        break;    
                    case 1:    
                        month=spring;    
                        break;    
                    case 2:    
                        month=spring;    
                        break;    
                    case 3:    
                        month=summer;    
                        break; 
                    case 4:    
                    	month=summer;    
                        break;    
                    case 5:    
                    	month=summer;    
                    	break;    
                    case 6:    
                    	month=fall;    
                    	break;    
                    case 7:    
                    	month=fall;    
                    	break; 
                    case 8:    
                    	month=fall;    
                    	break;
                    case 9:    
                    	month=winter;    
                    	break;    
                    case 10:    
                    	month=winter;    
                    	break; 
                    case 11:    
                    	month=winter;    
                    	break; 
                    };    
                        
                    return new Date(year,month,1);    
                }; 
                //昨天
                if($("#shortcutTime").val()=="1"){
                	var day1 = new Date();
                	day1.setTime(day1.getTime()-24*60*60*1000);
                	var s1 = day1.getFullYear()+"-" + (day1.getMonth()+1) + "-" + day1.getDate();
                	var start =s1+" 00:00:00";
                	var end =s1+" 23:59:59";
        			$('.form_datetimeStart').val(start);
        			$('.form_datetimeEnd').val(end);
                }
                //上周
                if($("#shortcutTime").val()=="2"){
                	var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6);
                	var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 0);
        			$('.form_datetimeStart').val(formatDate(weekStartDate)+" 00:00:00");
        			$('.form_datetimeEnd').val(formatDate(weekEndDate)+" 23:59:59");
                	 
                }
                //上月
                if($("#shortcutTime").val()=="3"){
                	var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
                	var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
        			$('.form_datetimeStart').val(formatDate(lastMonthStartDate)+" 00:00:00");
        			$('.form_datetimeEnd').val(formatDate(lastMonthEndDate)+" 23:59:59");
                }
                //上季度
                if($("#shortcutTime").val()=="4"){
                    var priorSeasonFirstDay =getPriorSeasonFirstDay(nowYear, nowMonth);
                    var priorSeasonLastDay = new Date(priorSeasonFirstDay.getFullYear(), priorSeasonFirstDay.getMonth() + 2, getMonthDays(lastMonth));
        			$('.form_datetimeStart').val(formatDate(priorSeasonFirstDay)+" 00:00:00");
        			$('.form_datetimeEnd').val(formatDate(priorSeasonLastDay)+" 23:59:59");
                }
                //上半年
                if($("#shortcutTime").val()=="5"){
                	var priorYearFirstDay = new Date(nowYear, 0, 1);
                	var priorYearEndDay = new Date(nowYear, 5, 30);
        			$('.form_datetimeStart').val(formatDate(priorYearFirstDay)+" 00:00:00");
        			$('.form_datetimeEnd').val(formatDate(priorYearEndDay)+" 23:59:59");
                }
                //去年
                if($("#shortcutTime").val()=="6"){
                    var priorYearFirstDay = new Date(nowYear--, 0, 1);
                    var priorYearLastDay = new Date(nowYear--, 0, 1);
                    console.log(formatDate(priorYearFirstDay));
                    console.log(formatDate(priorYearLastDay));
                    $('.form_datetimeStart').val(formatDate(priorYearLastDay)+" 00:00:00");
        			$('.form_datetimeEnd').val(formatDate(priorYearFirstDay)+" 23:59:59");
                }
            })
        },

//		//点击下拉框----获取所有的产线
//		getProductLine : function(){
//			$.ajax({
//				url: ctx +'/factory/product/listAllProduct/get.mvc',
//			    type:"post", 
//			    aysnc: true,
//			    dataType:'json',
//			    data : '',
//			    success : function(data){
//		    		for (var i = 0; i < data.length; i++) {
//			    		 $("#myModal .line").append("<option value='"+data[i].pkId+"' >" + data[i].lineName + "</option>");
//			    	 };
//			    },
//			    error: function(XMLHttpRequest, textStatus, errorThrown){
//			    	alert("系统错误");
//			    }
//			});
//		},
		menuCloseBtn : function(){
			
	        $('#menu-close-btn').click(function() {
	        	setTimeout(function() {
	        		
	        		$(window).resize();
	        	}, 10)
	        	  
	        	})
		},
		_resizeWindow : function(){
			setTimeout(function() {
        		$(window).resize();
        	}, 10)
		},

        //获取30天的时间间隔
		getMonthDate : function(){
			$('.form_datetimeStart').val(new Date(new Date().getTime() - 24*60*60*1000).format('yyyy-MM-dd hh:mm:ss'));
			$('.form_datetimeEnd').val(new Date().format('yyyy-MM-dd hh:mm:ss'));
			$('.form_datetimeStart').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			}).on('changeDate', function(ev) {
				var begin = new Date($('.form_datetimeStart').val());
				var endTime = new Date($('.form_datetimeStart').val());
				var nextmonth = SystemCommon.getNextMonth(begin);
				var begintime = new Date(nextmonth);
				$('.form_datetimeEnd').datetimepicker('setStartDate',endTime);
				$('.form_datetimeEnd').datetimepicker('setEndDate',begintime);
			});
			$('.form_datetimeEnd').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			}).on('changeDate', function(ev) {
				var begin = new Date($('.form_datetimeEnd').val());
				var endTime = new Date($('.form_datetimeEnd').val());
				var lastmonth = SystemCommon.getlastmonth(begin);
				var begintime = new Date(lastmonth);
				$('.form_datetimeStart').datetimepicker('setStartDate',begintime);
				$('.form_datetimeStart').datetimepicker('setEndDate',endTime);
			});
		},
		
        //获取3个月的时间间隔
		getThridMonthDate : function(){
			$('.form_datetimeStart').val(new Date(new Date().getTime() - 24*60*60*1000*92).format('yyyy-MM-dd hh:mm:ss'));
			$('.form_datetimeEnd').val(new Date().format('yyyy-MM-dd hh:mm:ss'));
			$('.form_datetimeStart').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			});
			$('.form_datetimeEnd').datetimepicker({
				format : 'yyyy-mm-dd hh:ii:ss',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				endDate : new Date(),
				forceParse : true
			});
		},
		
		//获取亲6个月的时间
		getlastmonth : function (date){
			var lastmonth = new Date(date.getFullYear(),date.getMonth()+1,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds())
			var curdate = date.getDate();
			lastmonth.setDate(-6)//上一月，当前月为一月时这种写法会退到上一年十二月
			lastmonth.setDate(0)//上月最后一天
			var lastmax = lastmonth.getDate();
			if(curdate <= lastmax){//天值不大于上月最大一天，天值同步
			lastmonth.setDate(curdate);
			}
			console.log(lastmonth);
			return lastmonth;
		},
		getNextMonth : function (currentDate) { 
			var date  = new Date(currentDate);
            var year = date.getFullYear(); //获取当前日期的年份  
            var month = date.getMonth()+6; //获取当前日期的月份  
            var day = date.getDate(); //获取当前日期的日  
            var year2 = year;  
            var month2 = parseInt(month) + 6;  
            if (month2 == 13) {  
                year2 = parseInt(year2) + 1;  
                month2 = 1;  
            }  
            var day2 = day;  
            var days2 = new Date(year2, month2, 0);  
            days2 = days2.getDate();  
            if (day2 > days2) {  
                day2 = days2;  
            }  
            if (month2 < 10) {  
                month2 = '0' + month2;  
            }
            var hour = date.getHours();
            var minute = date.getMinutes();
            var second = date.getSeconds();
            var t2 = year2 + '-' + month2 + '-' + day2 + " " + hour + ":" + minute + ":" + second;
            var nextMonth = new Date(t2);
            return nextMonth;  
        },
        
        //查询区域
        _queryLocation: function(){
        	$.ajax({
				 url:ctx+"/factory/area/listAllArea/get.mvc",
				 type:"get",
				 dataType:"json",
				 data:{},
				 success : function(response){
				    if (response.result == true) {
				    	var data =response.data;
				    	//循环厂区
				    	$(".queryArea").append("<option value='' >请选择</option>");
	                    for (var i = 0; i < data.length; i++) {
	                        $(".queryArea").append("<option value='"+data[i].locationCode+"' >" + data[i].locationName + "</option>");
	                    }
				    }else {
				    	DialogUtil.warning(response.message);
				    }
				    
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
				    DialogUtil.warning("系统错误");
				}
        	})
        	
        },
        
        //查询产线
        
        _queryLine: function(){
        	$.ajax({
				 url:ctx+"/factory/product/listAllLinesByFactoryId/get.mvc",
				 type:"get",
				 dataType:"json",
				 data:{},
				 success : function(response){
				    if (response.result == true) {
				    	var data =response.data;
				    	//循环厂区
				    	$(".queryLine").append("<option value='' >请选择</option>");
	                    for (var i = 0; i < data.length; i++) {
	                        $(".queryLine").append("<option value='"+data[i].lineCode+"' >" + data[i].lineName + "</option>");
	                    }
				    }else {
				    	DialogUtil.warning(response.message);
				    }
				    
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
				    DialogUtil.warning("系统错误");
				}
        	})
        	
        },
        //查询车间
        _queryShop: function(){
        	$.ajax({
				 url:ctx+"/factory/shop/listAllShopsByFactoryId/get.mvc",
				 type:"get",
				 dataType:"json",
				 data:{},
				 success : function(response){
				    if (response.result == true) {
				    	var data =response.data;
				    	//循环厂区
				    	$(".queryShop").append("<option value='' >请选择</option>");
	                    for (var i = 0; i < data.length; i++) {
	                        $(".queryShop").append("<option value='"+data[i].shopCode+"' >" + data[i].shopName + "</option>");
	                    }
				    }else {
				    	DialogUtil.warning(response.message);
				    }
				    
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
				    DialogUtil.warning("系统错误");
				}
        	})
        	
        },
        //查询用户
        _queryUser : function(){
        	//报告人搜索
			$(".queryUser").select2({
				  ajax: {
				    url: ctx +'/system/user/listAllUser/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          username: params.term,
				          num: params.page || 1,
				          size:10
				        };
				        return query;
				    },
				    processResults: function (result) {

				    	var equipModelArr =new Array();
				    	for ( var i = 0; i < result.data.length; i++) {
							var obj = new Object();
							obj.id=result.data[i].username;
							obj.text=result.data[i].truename;
							equipModelArr.push(obj);
						}
				    	var result = {
				    		results: equipModelArr,
				    		pagination :{
				    			more:result.result
				    		}
				    	};
				        return result;
				      },
				      cache: true
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0
			})
        }
		
		
	};
}(); 


//公共弹窗方法
var DialogUtil =function(){
	return {
		init : function(){

		},
		//確定取消弹框
		ok_and_cancel : function(message,okFunction,cancelFunction){
			
			//显示内容
			$(".ok_and_cancel .content").html(message);
			$(".ok_and_cancel .yes").unbind("click");
			$(".ok_and_cancel .yes").on("click",function(){
				if(typeof okFunction =="function"){
              	  okFunction();
                }
				$(".ok_and_cancel").modal('hide');
				$(".ok_and_cancel").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
					SystemCommon._resizeWindow();
				});
			});
			$(".ok_and_cancel .no").unbind("click");
			$(".ok_and_cancel .no").on("click",function(){
				if(typeof cancelFunction =="function"){
					cancelFunction();
                }
				$(".ok_and_cancel").modal('hide');
				$(".ok_and_cancel").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
					SystemCommon._resizeWindow();
				});
				
				
			});
			$(".ok_and_cancel").modal();
			
		},
		//確定取消弹框
		ok : function(message,okFunction){
			//显示内容
			console.log(message);
			$(".only_ok .content").html(message?message:'系统出错');
			$(".only_ok .yes").unbind("click");
			$(".only_ok .yes").on("click",function(){
				if(typeof okFunction =="function"){
              	  okFunction();            	  
                }
				$(".only_ok").modal('hide');
				$(".only_ok").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
					SystemCommon._resizeWindow();
				});
			});
			$(".only_ok").modal();
			
			},
		success : function(message){
			DialogUtil.ok(message);
			$(".ok_and_cancel").modal('hide');
			$(".ok_and_cancel").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
				SystemCommon._resizeWindow();
			});
		},
		warning : function(message){
			DialogUtil.ok(message);
			$(".ok_and_cancel").modal('hide');
			$(".ok_and_cancel").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
				SystemCommon._resizeWindow();
			});
		},
        warn : function(message){
            DialogUtil.ok(message);
            $(".ok_and_cancel").modal('hide');
            $(".ok_and_cancel").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
				SystemCommon._resizeWindow();
			});
        },
		error : function(message){
			DialogUtil.ok(message);
			$(".ok_and_cancel").modal('hide');
			$(".ok_and_cancel").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
				SystemCommon._resizeWindow();
			});
		}
		
		
	};
}();

Date.prototype.format = function(format)
{
 var o = {
 "M+" : this.getMonth()+1, //month
 "d+" : this.getDate(),    //day
 "h+" : this.getHours(),   //hour
 "m+" : this.getMinutes(), //minute
 "s+" : this.getSeconds(), //second
 "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
 "S" : this.getMilliseconds() //millisecond
 }
 if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
 (this.getFullYear()+"").substr(4 - RegExp.$1.length));
 for(var k in o)if(new RegExp("("+ k +")").test(format))
 format = format.replace(RegExp.$1,
 RegExp.$1.length==1 ? o[k] :
 ("00"+ o[k]).substr((""+ o[k]).length));
 return format;
}

jQuery(document).ready(function() {
	
	DialogUtil.init();
	SystemCommon.initClick();
});

